#' an interface with Programita software
#' 
#' @param com a community object
#' @param inter_mat a data.frame contains pairwise interspecific interactions
#' @param mark1,mark2 the name of marks in the given community
#' @param filename the filename of the output file
#' @param LINUX whether the out file is used in Linux OS, change the change line char correspondingly.
#' 
#' 
#' @usage 
#' write_community_file(com,mark1=NA,mark2=NA,filename="sim",LINUX=FALSE)
#' write_dissimilarity_file(inter_mat,filename="inter_mat",LINUX=FALSE)
#' 
#' @examples 
#' com=rcommunity()
#' com$dd=runif(30,0,1)
#' 
#' write_community_file(com,mark1="dd")
#' 
#' @export
write_community_file=function(com,mark1=NA,mark2=NA,filename="sim",LINUX=FALSE){
  plotdim=plotdim(com)
  N=total_abundance(com)
  
  if (LINUX) 
    eol = "\r\n"
  else eol = "\n"
  plotinf = matrix(c(0, plotdim[1], 0, plotdim[2], N), nrow = 1, ncol = 5)
  if(is.na(mark1) & is.na(mark2)){
    file_ext=".dat"
  }else{
    file_ext=".mcf"
  }
  
  write.table(plotinf, paste(filename, file_ext, sep = ""), row.names = FALSE, 
              col.names = FALSE, eol = eol, sep="\t")
  
  if(is.na(mark1) & is.na(mark2)){
    points = cbind(com$x, com$y,rep(1,N),com$species)
    write.table(points, paste(filename, file_ext, sep = ""), row.names = FALSE, 
                col.names = FALSE, eol = eol, append = TRUE, quote = FALSE, sep="\t")
  }else{
    if (!is.na(mark1) & is.na(mark2)){
      mv1=get_traits(com,mark1,drop=TRUE)
      mv2=rep(0,length(mv1))
    }else if(is.na(mark1) & !is.na(mark2)){
      mv1=get_traits(com,mark2,drop=TRUE)
      mv2=rep(0,length(mv1))
    }
    points = round(cbind(com$x, com$y,rep(1,N),mv1,mv2),3)
  } 
  write.table(points, paste(filename, file_ext, sep = ""), row.names = FALSE, 
              col.names = FALSE, eol = eol, append = TRUE, quote = FALSE, sep="\t")

}

write_dissimilarity_file=function(inter_mat,filename="inter_mat",LINUX=FALSE){
  if (LINUX) 
    eol = "\r\n"
  else eol = "\n"
  S=dim(inter_mat)[1]
  spnames=paste("SPECI",1:S,sep="")
  da=data.frame(rep(spnames,each=S),rep(spnames,S),as.numeric(as.matrix(inter_mat)))
  da=da[da[,1]!=da[,2],]
  write.table(da, paste(filename, ".dat", sep = ""), row.names = FALSE, 
              col.names = FALSE, eol = eol, quote = FALSE, sep="\t")
}